package com.yycx.sharding.demo.algorithm;

import com.yycx.starter.shardingjdbc.base.MyStandardShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 自定义标准分片算法
 *
 * @author zyf
 */
@Component
public class CustomModTableShardAlgorithm implements MyStandardShardingAlgorithm {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        for (String name : collection) {
            //对应c
            Long value = preciseShardingValue.getValue();
            //根据值进行取模，得到一个目标值
            if (name.endsWith(String.valueOf(value % 4))) {
                return name;
            }
        }
        throw new UnsupportedOperationException();
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return collection;
    }
}